package com.johnny.xia.sothebys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.johnny.xia.util.http.HttpClientUtil;
import com.johnny.xia.util.http.HttpReturnCommand;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.mountcloud.graphql.GraphqlClient;
import org.mountcloud.graphql.request.query.DefaultGraphqlQuery;
import org.mountcloud.graphql.request.query.GraphqlQuery;
import org.mountcloud.graphql.request.result.ResultAttributtes;
import org.mountcloud.graphql.response.GraphqlResponse;

import java.io.IOException;
import java.util.*;

public class DownloadData {

    static String url="https://proxyapi-prod.sothebys.cn/graphql";

    static Map<String,String> metadataKey = new HashMap<>();

    static Map<String,String> vtMap = new HashMap<>();
    static{
        vtMap.put("ObjectMetadataStringValue","String");
        vtMap.put("ObjectMetadataFloatValue","Float");
        vtMap.put("ObjectMetadataBooleanValue","Boolean");
        vtMap.put("ObjectMetadataIntegerValue","Int");
        vtMap.put("ObjectMetadataStringValues","StringArray");
    }

    public static void main(String[] args) throws Exception {
        List<String> auctionids = auctions(160);
        int count = 1;
        for(String str : auctionids){
            System.out.println("拉取第" + (count)+" get acution " + str + "开始");
            auction(str);
            System.out.println("拉取第" + (count++)+" get acution " + str + "结束");
        }

        System.out.println("拉取结束~~~~~~~~~~~~~~~~~~~");
        System.out.println(metadataKey.size());
        System.out.println(JSON.toJSONString(metadataKey));


    }


    public static String doPostBodyData(String url, String bodyData) throws Exception{
        String result = "";
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url); // 请求地址
            httpPost.addHeader("Content-Type","application/json");
            httpPost.setEntity(new StringEntity(bodyData, "UTF-8"));
            httpClient = HttpClients.createDefault();
            // 得到返回的response
            response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            String body = EntityUtils.toString(entity, "UTF-8");
            response.close();
            return body;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭httpClient
            if (null != httpClient) {
                httpClient.close();
            }
            // 关闭response
            if (null != response) {
                EntityUtils.consume(response.getEntity()); // 会自动释放连接
                response.close();
            }
        }
        return null;
    }


    public static void auction(String id) throws IOException{

        GraphqlClient client = GraphqlClient.buildGraphqlClient(url);
        Map httpHeaders = new HashMap<>();
        httpHeaders.put("Content-Type","application/json");
        client.setHttpHeaders(httpHeaders);
        GraphqlQuery query = new DefaultGraphqlQuery("auction");
        query.addParameter("id",id);
        ResultAttributtes resAttr = new ResultAttributtes("lotCards(filter:ALL)");
        ResultAttributtes lotId = new ResultAttributtes("lotId");
        ResultAttributtes objects = new ResultAttributtes("objects");
        ResultAttributtes metadata = new ResultAttributtes("metadata");
        metadata.addResultAttributes("key");

        ResultAttributtes _valueAttr = new ResultAttributtes("value");
        _valueAttr.addResultAttributes("__typename");

        metadata.addResultAttributes(_valueAttr);
        objects.addResultAttributes(metadata);
        resAttr.addResultAttributes(lotId,objects);
        query.addResultAttributes(resAttr);

        GraphqlResponse response = client.doQuery(query);
        Map map = response.getData();
        String jsonData = JSON.toJSONString(map);

        JSONObject json = JSON.parseObject(jsonData);
        JSONArray lotCards = json.getJSONObject("data").getJSONObject("auction").getJSONArray("lotCards");
        for(int i=0;i<lotCards.size();i++){
            JSONObject jo = lotCards.getJSONObject(i);
            JSONArray objectsTmp = jo.getJSONArray("objects");
            JSONObject objTmp = objectsTmp.getJSONObject(0);
            JSONArray metaDataArray = objTmp.getJSONArray("metadata");
            for(int j=0;j<metaDataArray.size();j++){
                JSONObject objT = metaDataArray.getJSONObject(j);
                String keyTmp = objT.getString("key");

                String _valueType = objT.getJSONObject("value").getString("__typename");

                String _vt = vtMap.get(_valueType);

                String mapV = metadataKey.get(keyTmp);
                if(mapV != null && !mapV.equals(_vt)){
                    throw new RuntimeException("key一样，类型不一样"+ keyTmp+"--"+_vt +"-->"+mapV);
                }
                metadataKey.put(keyTmp,_vt);
            }
        }

    }


    public static List<String> auctions(int take) throws IOException {


        List<String> res = new ArrayList<>();
        GraphqlClient client = GraphqlClient.buildGraphqlClient(url);
        Map httpHeaders = new HashMap<>();
//        httpHeaders.put("Authorization",token);
        httpHeaders.put("Content-Type","application/json");
        client.setHttpHeaders(httpHeaders);
        GraphqlQuery query = new DefaultGraphqlQuery("upcomingAuctions");
        query.addParameter("take",take);
        query.addResultAttributes("auctionId");
        GraphqlResponse response = client.doQuery(query);

        Map map = response.getData();

        JSONObject json = JSON.parseObject(JSON.toJSONString(map));

        JSONArray array = json.getJSONObject("data").getJSONArray("upcomingAuctions");

        for(int i=0;i<array.size();i++){
            JSONObject jo = array.getJSONObject(i);
            res.add(jo.getString("auctionId"));
        }

        return res;

    }


}
